package com.example.assisteddriving.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.telephony.SmsManager;
import android.util.Log;

import androidx.annotation.Nullable;

import com.example.assisteddriving.Xinlv;
import com.example.assisteddriving.Zhuye;
import com.example.assisteddriving.dao.DrivelogDao;
import com.example.assisteddriving.util.LocationUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class Xinlvservice extends Service {
    ServerSocket ss;
    Socket socket;
    Thread xinlvthread;
    Runnable xinlvtask;
    private Message msg;
    String phoneNuml;
    public static final String PREFERENCE_NAME = "gerenxinxi";  //文件名
    public static int MODE = MODE_PRIVATE;  //操作模式
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_NAME, MODE);
        phoneNuml = sharedPreferences.getString("jinjidianhua", null);
        xinlvtask=new Runnable() {
            @Override
            public void run() {
                try {
                    ss = new ServerSocket(10010);
                    List<String> list=new ArrayList<>();
                    while(true) {
                        Log.v("asd","等待测量心率");
                       socket= ss.accept();
                        Log.v("asd","测量心率已连接");
                        BufferedReader br = null;
                        br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String line = br.readLine();
                        Log.v("asd",line);
                        list.add(line);
                        //解析传来的字符串 80/36/100
                        if (list.size()==10) {
                            float fxl = 0, fxy=0;
                            double ftw=0;
                            for (int n = 0; n < 10; n++) {
                                String xl = null, tw = null, xy = null;
                                char a[] = list.get(n).toCharArray();
                                char b[] = new char[10];
                                int j = 0;
                                for (int i = 0; i < list.get(n).length(); i++) {
                                    if (a[i] == ' ' && i < 4) {
                                        xl = new String(b);
                                        fxl = fxl+Float.parseFloat(xl);
                                       // Log.v("dsa", String.valueOf(fxl));
                                        b=new char[10];
                                        j = 0;
                                        i++;
                                    } else if (a[i] == ' ' && i < 10) {
                                        tw = new String(b);
                                        ftw = ftw+Double.parseDouble(tw);
                                        Log.v("dsa", String.valueOf( ftw));
                                        b=new char[10];
                                        j = 0;
                                        i++;
                                    } else if (a[i] == ' ' && i < 14) {
                                        xy = new String(b);
                                        fxy = fxy+Float.parseFloat(xy);
                                        //Log.v("dsa", String.valueOf(fxy));
                                        j = 0;
                                    }
                                    b[j] = a[i];
                                    j++;
                                }
                            }
                            ftw=(int)(ftw*10);
                            String sj=gettime();
                            DrivelogDao drivelogDao = new DrivelogDao(Xinlvservice.this);
                            drivelogDao.insertxinlv(String.valueOf(fxl/10), String.valueOf(ftw/100), String.valueOf(fxy/10), sj);//(ftw+550)/100
                            msg = new Message(); //也可msg = Message.obtain();
                            msg.what = 0x003; //设置消息类型
                            Bundle data1 = new Bundle(); //生成Bundle对象携带数据
                            data1.putString("xinlv", String.valueOf(fxl/10));
                            data1.putString("tiwen", String.valueOf(ftw/100));
                            data1.putString("xueyang", String.valueOf(fxy/10));
                            data1.putString("time", sj);
                            msg.setData(data1);
                            Xinlv.myHandler.sendMessage(msg);
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            list.clear();
                            //||(ftw<36.2||ftw>37.2)
                            if ((fxl/10<50||fxl/10>100)){
                                LocationUtils locationUtils=new LocationUtils();
                                //sendSMS2(phoneNuml,"在"+locationUtils.getLocations(getBaseContext())+"此用户身体健康指标异常，请您及时询问情况！");
                                callPhone();
                            }
                        }
                    }
                } catch (IOException e){
                    e.printStackTrace();
                }
                finally {
                    try {
                        //关闭输入流、socket
                        if(socket!=null)    socket.close();
                        if(ss!=null) ss.close();
                    } catch (IOException e) {    e.printStackTrace(); }
                }
            }
        };
        xinlvthread=new Thread(xinlvtask);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(!xinlvthread.isAlive()){
            xinlvthread.start();
        }

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        if(xinlvthread.isAlive()) {
            Log.v("asd", "心率服务已结束");
            try {
                //关闭输入流、socket
                if(socket!=null)    socket.close();
                if(ss!=null) ss.close();
            } catch (IOException e) {    e.printStackTrace(); }
        }
        super.onDestroy();
    }

    public String gettime(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
//        System.out.println("time => " + dateFormat.format(cal.getTime()));

        return dateFormat.format(cal.getTime());

    }
    public void sendSMS2(String phoneNumber,String message) {

        if (!phoneNumber.isEmpty() && !message.isEmpty()) {
            SmsManager smsManager = SmsManager.getDefault();
            ArrayList<String> strings = smsManager.divideMessage(message);
            for (int i = 0; i < strings.size(); i++) {
                smsManager.sendTextMessage(phoneNumber, null, message, null, null);
            }
            Log.v("asd","短信已发送");
        } else {
            Log.v("asd","手机号不能为空");
            return;
        }
    }
    public void callPhone(){

        Log.v("asd",phoneNuml);
        //如果需要手动拨号将Intent.ACTION_CALL改为Intent.ACTION_DIAL（跳转到拨号界面，用户手动点击拨打）
        Intent intent =new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNuml));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
        startActivity(intent);
    }
}
